import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mlkit_barcode_scanning/google_mlkit_barcode_scanning.dart';
import 'package:image_picker/image_picker.dart';
import 'package:matuo/ble/ScanBluetoothUtil.dart';

import '../../utils/Logcat.dart';

class QrPage extends StatefulWidget {
  const QrPage({super.key, required this.camera});

  final CameraDescription camera;

  @override
  State<StatefulWidget> createState() {
    return _QrPageState();
  }
}

class _QrPageState extends State<QrPage> {
  final _orientations = {
    DeviceOrientation.portraitUp: 0,
    DeviceOrientation.landscapeLeft: 90,
    DeviceOrientation.portraitDown: 180,
    DeviceOrientation.landscapeRight: 270,
  };
  final BarcodeScanner _barcodeScanner = BarcodeScanner();
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    setupCameras();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> setupCameras() async {
    _controller = CameraController(
      widget.camera,
      ResolutionPreset.high,
      enableAudio: false,
      imageFormatGroup: Platform.isAndroid
          ? ImageFormatGroup.nv21
          : ImageFormatGroup.bgra8888,
    );
    _initializeControllerFuture = _controller.initialize().then((value) async {
      _controller.startImageStream(_processCameraImage);
      _controller.setFlashMode(FlashMode.auto);
      _isProcessImage = false;
    });

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: null,
        extendBodyBehindAppBar: true,
        extendBody: true,
        backgroundColor: Colors.transparent,
        body: Stack(children: [
          FutureBuilder<void>(
              future: _initializeControllerFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Transform.scale(
                    scale: 1.5,
                    alignment: Alignment.topCenter,
                    child: CameraPreview(_controller),
                  );
                } else {
                  // Otherwise, display a loading indicator.
                  return const Center(child: CircularProgressIndicator());
                }
              }),
          // DraggableImage(),
        ]));
  }

  void _processCameraImage(CameraImage image) {
    final inputImage = _inputImageFromCameraImage(image);
    if (inputImage == null) {
      return;
    }
    _analysisImage(inputImage);
  }

  InputImage? _inputImageFromCameraImage(CameraImage image) {
    if (_controller == null) return null;

    final sensorOrientation = widget.camera.sensorOrientation;
    InputImageRotation? rotation;
    if (Platform.isIOS) {
      rotation = InputImageRotationValue.fromRawValue(sensorOrientation);
    } else if (Platform.isAndroid) {
      var rotationCompensation =
          _orientations[_controller!.value.deviceOrientation];
      if (rotationCompensation == null) return null;
      if (widget.camera.lensDirection == CameraLensDirection.front) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
      } else {
        rotationCompensation =
            (sensorOrientation - rotationCompensation + 360) % 360;
      }
      rotation = InputImageRotationValue.fromRawValue(rotationCompensation);
    }
    if (rotation == null) return null;

    final format = InputImageFormatValue.fromRawValue(image.format.raw);
    if (format == null) {
      return null;
    }
    if ((Platform.isAndroid && format != InputImageFormat.nv21)) {
      return null;
    }
    if ((Platform.isIOS && format != InputImageFormat.bgra8888)) {
      return null;
    }

    if (image.planes.length != 1) {
      return null;
    }
    final plane = image.planes.first;

    return InputImage.fromBytes(
      bytes: plane.bytes,
      metadata: InputImageMetadata(
        size: Size(image.width.toDouble(), image.height.toDouble()),
        rotation: rotation, // used only in Android
        format: format, // used only in iOS
        bytesPerRow: plane.bytesPerRow, // used only in iOS
      ),
    );
  }

  bool _isProcessImage = false;

  //开始解码二维码
  void _analysisImage(InputImage inputImage) async {
    final barcodes = await _barcodeScanner.processImage(inputImage);
    if (barcodes.isEmpty) {
      return;
    }

    if (_isProcessImage) {
      return;
    }
    _isProcessImage = true;
    List<String> list =
        barcodes.map((barcode) => barcode.displayValue ?? '').toList();
    Logcat.instance.d("二维码内容：${list.first}");

    RegExp regExp = RegExp(
      r"https://matuofit.matuoo.com/download\?mac=([\w:]{17})&pid=(\d+)&name=(.*)",
    );

    // 使用正则表达式匹配 URL
    Match? match = regExp.firstMatch(list.first);

    if (match != null) {
      String mac = match.group(1)!;
      String pid = match.group(2)!;
      String name = match.group(3)!;
      // 输出解析结果
      Logcat.instance.d('MAC: $mac');
      Logcat.instance.d('PID: $pid');
      Logcat.instance.d('Name: $name');
      ScanBluetoothUtil.instance.findMAC(mac);
    } else {
      Logcat.instance.d('没有匹配到任何内容');
    }

    // TODO 退出或跳转连接界面
    // pausePreview();
  }

  void pausePreview() {
    _controller?.pausePreview();
  }

  // 使用图片解码
  bool _isSelectingPhoto = false;
  void _selectPhoto() async {
    _isSelectingPhoto = true;
    ImagePicker imagePicker = ImagePicker();
    final pickedFile =
        await imagePicker!.pickImage(source: ImageSource.gallery);
    _isSelectingPhoto = false;
    if (pickedFile == null) {
      return;
    }
    Logcat.instance.d('二维码:pickFile${pickedFile.path}');
    final inputImage = InputImage.fromFilePath(pickedFile.path);
    _analysisImage(inputImage);
  }
}
